package com.dmall.promotion.controller;

import com.dmall.promotion.domain.User;
import com.dmall.promotion.service.UserService;
import com.dmall.promotion.utils.RandomUtils;
import com.dmall.promotion.utils.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户操作Controller
 * @author xiao1.wang
 * @date 2021-06-03 17:38:38
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/add")
    public Result save() {
        User user = new User();
        user.setId(RandomUtils.generateUserId());
        user.setName("xx" + user.getId());
        user.setAge(user.getId() % 20);
        user.setPhone("13888888888");
        user.setEmail(user.getName() + "@dmall.com");
        userService.add(user);
        Result result = new Result();
        result.setCode("0000");
        result.setMessage("保存成功");
        return result;
    }

    @GetMapping("/modify")
    public Result modify(@RequestParam("id") Integer id, @RequestParam("name") String name) {
        User user = userService.get(id);
        user.setName(name);
        userService.modify(user);
        Result result = new Result();
        result.setCode("0000");
        result.setMessage("修改成功");
        return result;
    }

    @GetMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        userService.delete(id);
        Result result = new Result();
        result.setCode("0000");
        result.setMessage("删除成功");
        return result;
    }

    @GetMapping("/list")
    public Result list() {
        List<User> userList = userService.userList();
        Result result = new Result();
        result.setCode("0000");
        result.setData(userList);
        result.setMessage("查询列表成功");
        return result;
    }
}
